#define _CRT_SECURE_NO_WARNINGS 1

#include <stdlib.h>
struct ListNode {
    int val;
    struct ListNode* next;
};

struct ListNode* partition(struct ListNode* pHead, int x)
{
    // write code here
    struct ListNode* gGuard, * gTail, * lGuard, * lTail;
    gGuard = gTail = (struct ListNode*)malloc(sizeof(struct ListNode));
    lGuard = lTail = (struct ListNode*)malloc(sizeof(struct ListNode));

    struct ListNode* cur = pHead;
    while (cur)
    {
        if (cur->val < x)
        {
            lTail->next = cur;
            lTail = lTail->next;
        }
        else
        {
            gTail->next = cur;
            gTail = gTail->next;
        }
        cur = cur->next;
    }

    lTail->next = gGuard->next;
    //gTail->next=NULL;

    struct ListNode* head = lGuard->next;
    free(lGuard);
    free(gGuard);
    return head;
}

int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode));
    n1->val = 1;
    n2->val = 5;
    n3->val = 2;
    n4->val = 7;
    n5->val = 3;
    n6->val = 4;
    n1->next = n2;
    n2->next = n3;
    n3->next = n4;
    n4->next = n5;
    n5->next = n6;
    n6->next = NULL;

    partition(n1, 5);
}